﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using WatiN.Core;
using System.Configuration;
using WatiN.Core.Native.InternetExplorer;
using System.IO;
using log4net;
using log4net.Config;
using System.Text.RegularExpressions;

namespace PlayerStat
{
    class ScrapeSweden : ScrapeSite
    {
        static int tempNumber = 1;
        ILog logger;
        private int leagueID = -1;
        private int maxRound = -1; //set the max round in one season
        private int countryID = -1;

        private string match_url_template = @"http://www.fotball.no/System-pages/TabellTermin/?tournamentId=125844";
        //private string match_stat_url_template = @"http://soccernet.espn.go.com/match?id={0}&cc=4716";
        //private string player_stat_url_template = @"http://soccernet.espn.go.com/gamecast/statistics?id={0}&cc=4716";
        private string league = string.Empty;

        public ScrapeSweden()
        {
            leagueID = -1;
            maxRound = 30;
            countryID = Leagues.SwedenID;

            logger = LogManager.GetLogger("scrape");

            if (logger == null)
            {
                throw new Exception("Null Logger");
            }
        }

        public void SetLeague(int nLeagueID)
        {
            leagueID = nLeagueID;

            switch (leagueID)
            {
                case 13:
                    league = "Allsvenskan";
                    break;
                default:
                    throw new Exception("Wrong League Number");
            }
        }

        public void SetMaxRound(int nMaxRound)
        {
            maxRound = nMaxRound;
        }

        public void SetMaxRoundBySeason(int year)
        {
            if (year <= 2007) maxRound = 26;
            else maxRound = 30;
        }

        // The Main Function, scrape webs
        public bool Scrape()
        {
            logger.Debug("#Scrape Sweden League# Start");
            IE mainIE = new IE();
            IE statIE = null;
            int iHomePageWaitTime = 20 * 1000; //set the wait time for each web, to avoid unexpected errors 
            int iMatchPageWaitTime = 30 * 1000; //set the wait time for each web, to avoid unexpected errors

            try
            {
                EventInit evnt = new EventInit(leagueID, maxRound,Leagues.SwedenID.ToString());
                string date = string.Empty;
                int round = 0;
                int year = 2007;
                string url = string.Empty;
                while (evnt.GetEventRound(leagueID, out year, out round, out date))
                {
                    logger.DebugFormat("Go to season {0}, round {1}", year, round);

                    SetMaxRoundBySeason(year);

                    // Get one season's match URL
                    url = GetAllMatchURL(year, leagueID);
                    //url = GetMatchURL(year, round);
                    //url = "E:\\temp\\2011Sweden.htm"; //for local test

                    mainIE.GoTo(url);
                    System.Threading.Thread.Sleep(iHomePageWaitTime);

                    //Get Match Date
                    Table tbl = null;
                    if (!GetMatchTable(mainIE, out tbl))
                    {
                        logger.Error("The validated match table is not found.");
                        continue;
                    }

                    DataTable matches = null;
                    if (!GetMatchList(tbl, year, round, out matches))
                    {
                        logger.ErrorFormat("Parse the match list of round {0} failed.", round);
                        continue;
                    }

                    foreach (DataRow dr in matches.Rows)
                    {
                        MatchData md = new MatchData();
                        md.LeagueID = this.leagueID;
                        md.MatchRound = round;
                        md.matchTime = (DateTime)dr["MatchTime"];
                        md.home = (string)dr["HomeTeam"];
                        md.homeID = (int)dr["HomeID"];
                        md.away = (string)dr["AwayTeam"];
                        md.awayID = (int)dr["AwayID"];
                        md.match.homeScore = (int)dr["HomeScore"];
                        md.match.awayScore = (int)dr["AwayScore"];

                        statIE = new IE();

                        logger.Info("GoTo URL:" + dr["MatchStatURL"].ToString());
                        statIE.GoTo(dr["MatchStatURL"].ToString()); 
                        //statIE.GoTo("e:\\temp\\SwedenNormal.htm"); // for local test
                        //statIE.GoTo("e:\\temp\\SwedenMatch2.htm"); // for local test

                        System.Threading.Thread.Sleep(iMatchPageWaitTime); // wait a longer time to ensure the table can be loaded correctly

                        // Full Match Stat Scrape, need to implement
                        if (!GetMatchStat(statIE, year, ref md))
                        {
                            statIE.Close();
                            logger.ErrorFormat("Error to get statistic in {0} vs {1}", md.home, md.away);
                            continue;
                        }
                        statIE.Close();
                        md.SaveToDB();

                    }
                    System.Threading.Thread.Sleep(3 * 1000);
                    evnt.NextRound();
                }
                logger.Debug("#Scrape Sweden League# End");
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("#Scrape Sweden League# Failed: Exception.");
                logger.Error(ex.ToString());
                return false;
            }
            finally
            {
                if (mainIE != null)
                {
                    mainIE.Close();
                }
                if (statIE != null)
                {
                    statIE.Close();
                }
            }
        }

        /// <summary>
        /// Get the match URL for the specified round/season
        /// </summary>
        /// <param name="year">season's start year</param>
        /// <param name="round">round no.</param>
        /// <returns>URL</returns>
        public string GetMatchURL(int year, int round)
        {
            logger.Debug("#GetMatchURL# Starts. [PARAM IN]Year:" + year.ToString() + ". Round:" + round.ToString());
            int iNextYear = year + 1;
            string strYear = year.ToString();
            string strNextYear = iNextYear.ToString().Substring(iNextYear.ToString().Length - 2, 2);
            string strURL = string.Format(match_url_template, strYear, strNextYear, round);
            logger.Debug("#GetAllMatchURL# Ends. [PARAM OUT] URL:" + strURL);

            return strURL;
        }

        /// <summary>
        /// Get the match URL for the all round of specified season
        /// </summary>
        /// <param name="year">season's start year</param>
        /// <returns>URL</returns>
        public string GetAllMatchURL(int year, int leagueID)
        {
            logger.Debug("#GetAllMatchURL# Starts. [PARAM IN]Year:" + year.ToString());

            string strURL = string.Empty;
            switch (leagueID)
            {
                case 13:
                    {
                        league = "Allsvenskan";
                        if (2006 == year) strURL = @"http://svenskfotboll.se/allsvenskan/tidigare-ar/resultat-2006/tabell/?scr=fixturelist&ftid=516";
                        else if (2007 == year) strURL = @"http://svenskfotboll.se/allsvenskan/tidigare-ar/resultat-2007/tabell/?scr=fixturelist&ftid=641";
                        else if (2008 == year) strURL = @"http://svenskfotboll.se/allsvenskan/tidigare-ar/resultat-2008/tabell-resultat/?scr=fixturelist&ftid=14999";
                        else if (2009 == year) strURL = @"http://svenskfotboll.se/allsvenskan/tidigare-ar/thylins-allsvenska-summering-2009/tabell-och-resultat/?scr=fixturelist&ftid=19440";
                        else if (2010 == year) strURL = @"http://svenskfotboll.se/allsvenskan/tidigare-ar/resultat-2010/tabell-och-resultat/?scr=fixturelist&ftid=27018";
                        else if (2011 == year) strURL = @"http://svenskfotboll.se/allsvenskan/tidigare-ar/resultat-2011/tabell-och-resultat/?scr=fixturelist&ftid=31625";
                        break;
                    }
                default:
                    throw new Exception("Wrong League Number");
            }

            logger.Debug("#GetAllMatchURL# Ends. [PARAM OUT] URL:" + strURL);

            return strURL;
        }

        /// <summary>
        /// Get a season's all match data into mTable
        /// </summary>
        /// <param name="ie">The ie web which has a season's all match data</param>
        /// <returns>mTable</returns>
        public bool GetMatchTable(IE ie, out Table mTable)
        {
            logger.Debug("#GetMatchTable# Starts.");

            // ONLY one table here

            if (ie.Tables[0].TableCells[0].Text.ToUpper() != "SPELPROGRAM")
            {
                mTable = null;
                logger.Debug("#GetMatchTable# Ends. Return:false.");
                return false;
            }
            else
            {
                mTable = ie.Tables[0];
                logger.Debug("#GetMatchTable# Ends. Return:true.");
                return true;
            }
        }

        /// <summary>
        /// Scrape the Matches List of each round
        /// </summary>
        /// <param name="tbl">The table which has a season's all match data</param>
        /// <param name="year">The specified season, different season may have different team account</param>
        /// <param name="round">The specified round</param>
        /// <returns>mTable</returns>
        public bool GetMatchList(Table tbl, int year, int round, out DataTable mTable)
        {
            logger.Debug("#GetMatchList# Starts. Round:" + round.ToString());
           
            try
            {
                mTable = new DataTable();
                if (round > maxRound)
                {
                    logger.Debug("#GetMatchList# Ends. Return:true.");
                    return true;
                }

                mTable.Columns.Add("MatchTime", typeof(DateTime));
                mTable.Columns.Add("HomeTeam", typeof(string));
                mTable.Columns.Add("HomeID", typeof(int));
                mTable.Columns.Add("HomeScore", typeof(int));
                mTable.Columns.Add("AwayTeam", typeof(string));
                mTable.Columns.Add("AwayID", typeof(int));
                mTable.Columns.Add("AwayScore", typeof(int));
                mTable.Columns.Add("MatchStatURL", typeof(string));

                DateTime dtPreTime = DateTime.Parse("9999/12/31");
                int iMatchesPerRound = 0;
                int i = 0;

                if (year <= 2007)
                {
                    iMatchesPerRound = 7;
                }
                else
                {
                    iMatchesPerRound = 8;
                }
                i = 3 + (round - 1) * (iMatchesPerRound + 1); // add 1 for round title, start is line 3

                while( i < tbl.TableRows.Count )
                {
                    string strRoundTitle = tbl.TableRows[i].TableCells[0].Text;

                    #region generate match data
                    if (strRoundTitle.Equals("Omgång " + round.ToString())
                        || strRoundTitle.Equals("Omgång" + round.ToString())) // the specified round
                    {
                        #region add each match data for specified round
                        for (int j = 1; j <= iMatchesPerRound; j++)
                        {
                            TableRow tr = tbl.TableRows[i + j];
                            DataRow dr = mTable.NewRow();

                            DateTime dtMatchTime;
                            string strHomeTeam = "";
                            string strAwayTeam = "";
                            int iHomeScore = -1;
                            int iAwayScore = -1;
                            string strMatchURL = "";

                            if (tr.TableCells[0].Text.Trim() != string.Empty) // Match Time
                            {
                                string strDateTime = tr.TableCells[0].Text.Trim();
                                dtPreTime = Translate.TransSwedenDateTime(strDateTime);
                            }
                            dtMatchTime = dtPreTime;

                            string strTeam = tr.TableCells[1].Text.Trim();
                            string[] strTeams = strTeam.Split('-');

                            if (strTeams.Length != 2)
                            {
                                throw new Exception("Can not parse match teams.");
                            }

                            strHomeTeam = strTeams[0].Trim();
                            strAwayTeam = strTeams[1].Trim();

                            string strScore = tr.TableCells[2].Text;
                            string[] strScores = strScore.Split('-');
                            if (strScores.Length != 2)
                            {
                                throw new Exception("Can not parse match score.");
                            }

                            if (strScores[0].Trim().Equals("-")) // Match which is in future
                            {
                                logger.Debug("#GetMatchList# Ends. Return:true.");
                                return true;
                            }

                            iHomeScore = int.Parse(strScores[0].Trim());
                            iAwayScore = int.Parse(strScores[1].Trim());
                            strMatchURL = tr.TableCells[2].Links.First().Url;

                            dr["MatchTime"] = dtMatchTime;
                            dr["HomeTeam"] = strHomeTeam;
                            //dr["HomeID"] = GetID(tr.TableCells[1].Links[0].Url);
                            dr["HomeID"] = -1;
                            dr["HomeScore"] = iHomeScore;
                            dr["AwayTeam"] = strAwayTeam;
                            //dr["AwayID"] = GetID(tr.TableCells[3].Links[0].Url);
                            dr["AwayID"] = -1;
                            dr["AwayScore"] = iAwayScore;
                            dr["MatchStatURL"] = strMatchURL;
                            mTable.Rows.Add(dr);
                        }
                        #endregion add each match data for specified round

                        break;
                    }
                    #endregion generate match data

                    i += (iMatchesPerRound + 1);
                }

                logger.Debug("#GetMatchList# Ends. Return:true.");
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("#GetMatchList# Failed: Exception.");
                logger.Error(ex.ToString());
                mTable = null;

                logger.Debug("GetMatchTable Ends. Return:false.");
                return false;
            }
        }

        // Get the playerID
        private int GetPlayerID(string str)
        {
            string temp = str.Remove(0, @"http://www.fotball.no/Community/Profil/?fiksId=".Length);
            try 
            {
                return int.Parse(temp);
            }
            catch (Exception ex)
            {
                logger.Warn("#GetPlayerID# Invalid data source." + ex.ToString());               
                return 0;
            }         
        }

        /// <summary>
        /// Scrape each match's statistic
        /// </summary>
        /// <param name="tbl">The table which has a season's all match data</param>
        /// <param name="round">The specified round</param>
        /// <returns>mTable</returns>
        private bool GetMatchStat(IE ie, int year, ref MatchData md)
        {
            logger.Debug("#GetMatchStat# Starts.");
            try
            {
                Table tblHomeLineUps = null;
                Table tblHomeSubs = null;
                Table tblAwayLineUps = null;
                Table tblAwaySubs = null;
                Table tblMatchFacts = null;

                if (year == 2011) // special name for season 2011
                {
                    tblHomeLineUps = ie.Table(Find.ByClass("clCommonGrid") && Find.ByIndex(0));
                    tblHomeSubs = ie.Table(Find.ByClass("clCommonGrid") && Find.ByIndex(1));
                    tblAwayLineUps = ie.Table(Find.ByClass("clCommonGrid") && Find.ByIndex(2));
                    tblAwaySubs = ie.Table(Find.ByClass("clCommonGrid") && Find.ByIndex(3));
                    tblMatchFacts = ie.Table(Find.ByClass("clTblStatBox") && Find.ByIndex(0));
                }
                else 
                {
                    tblHomeLineUps = ie.Table(Find.ByClass("clTblStatBox") && Find.ByIndex(1));
                    tblHomeSubs = ie.Table(Find.ByClass("clTblStatBox") && Find.ByIndex(2));
                    tblAwayLineUps = ie.Table(Find.ByClass("clTblStatBox") && Find.ByIndex(3));
                    tblAwaySubs = ie.Table(Find.ByClass("clTblStatBox") && Find.ByIndex(4));
                    tblMatchFacts = ie.Table(Find.ByClass("clTblStatBox") && Find.ByIndex(0));
                }

                if (!tblHomeLineUps.Exists
                    || !tblHomeSubs.Exists
                    || !tblAwayLineUps.Exists
                    || !tblAwaySubs.Exists
                    || !tblMatchFacts.Exists)
                {
                    throw new Exception("The table of team data is not found");
                }

                if (false == GetTeamStat(tblHomeLineUps, true, ref md.match, ref md.homeplayers) || // get home team's match statistic
                    false == GetTeamStat(tblAwayLineUps, false, ref md.match, ref md.awayplayers)) // get away team's match statistic
                {
                    logger.Debug("#GetMatchStat# Ends. Return:false.");
                    return false;
                }

                if (false == GetPlayerStat(tblMatchFacts, ref md.match, ref md.homeplayers, ref md.awayplayers)) // get home team's match statistic
                {
                    logger.Debug("#GetMatchStat# Ends. Return:false.");
                    return false;
                }

                logger.Debug("#GetMatchStat# Ends. Return:true");
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("#GetMatchStat# Failed: Exception");
                logger.Error(ex.ToString());

                logger.Debug("#GetMatchStat# Ends. Return:false.");
                return false;
            }
        }

        private bool GetTeamStat(Table tblPlayers,bool isHomeTeam, ref MatchStat match, ref Dictionary<int, PlayerStat> players)
        {
            logger.Debug("#GetTeamStat# Starts.");

            try
            {
                int iCount = 0;

                // for Line-up
                foreach (TableRow tr in tblPlayers.TableRows)
                {
                    if (tr.TableCells.Count != 2) continue;

                    if (iCount >= 11)
                    {
                        break;
                    }

                    int number = GenPlayerNumber();
                    PlayerStat player = new PlayerStat();
                    player.playerName = GetSafeString(tr.TableCells[1].Text.Trim());
                    //if (!player.playerName.Equals(string.Empty))
                    //{
                    //    string strPlayerURL = tr.TableCells[1].Links.First().Url;
                    //    player.playerID = GetPlayerID(strPlayerURL);
                    //}
                    player.isPlayerSub = false;
                    players.Add(number, player);
                    iCount++;                   
                }

                return true;

            }
            catch (Exception ex)
            {
                logger.Error("#GetTeamStat# Failed: Exception");
                logger.Error(ex.ToString());

                logger.Debug("#GetTeamStat# Ends. Return:false.");
                return false;
            }
        }

        private bool GetPlayerStat(Table tblMatchFacts, ref MatchStat match, ref Dictionary<int, PlayerStat> homePlayers, ref Dictionary<int, PlayerStat> awayPlayers)
        {
            logger.Debug("#GetPlayerStat# Starts.");

            try
            {
                foreach (TableRow tr in tblMatchFacts.TableRows)
                {
                    if (tr.TableCells.Count != 7) continue;

                    bool bHomeTeam = false;
                    string strItemType = string.Empty;

                    if (tr.TableCells[0].Images.Count != 0)
                    {
                        bHomeTeam = true;
                        strItemType = tr.TableCells[0].Images[0].Src;
                    }
                    else if (tr.TableCells[6].Images.Count != 0)
                    {
                        bHomeTeam = false;
                        strItemType = tr.TableCells[6].Images[0].Src;
                    }

                    #region HomeTeam
                    if (true == bHomeTeam)
                    {
                        if (strItemType.Contains("goal.gif"))
                        {
                            string strPlayer = tr.TableCells[1].Text;
                            int iIndex = strPlayer.IndexOf('(');
                            string strGoalPlayer = (iIndex != -1) ? strPlayer.Remove(strPlayer.IndexOf('(')).Trim() : strPlayer.Trim();
                            string strGoalMin = tr.TableCells[3].Text.Trim();
                            strGoalMin = strGoalMin.Contains("90") ? "90" : strGoalMin;

                            bool bIsOwnGoal = false;

                            foreach (KeyValuePair<int, PlayerStat> kv in homePlayers)
                            {
                                if (strGoalPlayer == kv.Value.playerName)
                                {
                                    MinuteStat ms = new MinuteStat();
                                    ms.goalMin = Int32.Parse(strGoalMin);

                                    ms.isOwnGoal = false;
                                    ms.name = strGoalPlayer;
                                    kv.Value.MinStat.Add(ms);
                                    kv.Value.goal++;

                                    bIsOwnGoal = false;
                                    break;
                                }
                            }
                        }
                        else if (strItemType.Contains("yellowcard.gif"))
                        {
                            string strCardPlayer = tr.TableCells[1].Text.Trim();
                            string strCardMin = tr.TableCells[3].Text.Trim();

                            foreach (KeyValuePair<int, PlayerStat> kv in homePlayers)
                            {
                                if (strCardPlayer == kv.Value.playerName)
                                {
                                    match.homeYCard++; // red card
                                    kv.Value.yellowCard++;
                                    break;
                                }
                            }
                        }
                        else if (strItemType.Contains("redcard.gif"))
                        {
                            string strCardPlayer = tr.TableCells[1].Text.Trim();
                            string strCardMin = tr.TableCells[3].Text.Trim();

                            foreach (KeyValuePair<int, PlayerStat> kv in homePlayers)
                            {
                                if (strCardPlayer == kv.Value.playerName)
                                {
                                    match.homeRCard++; // red card
                                    kv.Value.redCard++;
                                    break;
                                }
                            }
                        }
                        else if (strItemType.Contains("substition.gif"))
                        {
                            string strSubFacts = tr.TableCells[1].Text.Trim();
                            string[] separator = { "\r\n" };
                            string[] strPlayers = strSubFacts.Split(separator, System.StringSplitOptions.RemoveEmptyEntries);

                            string strSwitchoutPlayer = strPlayers[0].Remove(strPlayers[0].IndexOf('(')).Trim();
                            string strSubPlayer = strPlayers[1].Remove(strPlayers[0].IndexOf('(')).Trim();

                            PlayerStat subPlayer = new PlayerStat();
                            subPlayer.playerName = strSubPlayer;
                            subPlayer.isPlayerSub = true;
                            int number = GenPlayerNumber();
                            homePlayers.Add(number, subPlayer);

                            foreach (KeyValuePair<int, PlayerStat> kv in homePlayers)
                            {
                                if (strSwitchoutPlayer == kv.Value.playerName)
                                {
                                    kv.Value.isSwitchOut = true;
                                    break;
                                }
                            }
                        }
                    }
                    #endregion HomeTeam
                    #region AwayTeam
                    else
                    {
                        if (strItemType.Contains("goal.gif"))
                        {
                            string strPlayer = tr.TableCells[5].Text;
                            int iIndex = strPlayer.IndexOf('(');
                            string strGoalPlayer = (iIndex != -1) ? strPlayer.Remove(strPlayer.IndexOf('(')).Trim() : strPlayer.Trim();
                            string strGoalMin = tr.TableCells[3].Text.Trim();
                            strGoalMin = strGoalMin.Contains("90") ? "90" : strGoalMin;

                            bool bIsOwnGoal = false;

                            foreach (KeyValuePair<int, PlayerStat> kv in awayPlayers)
                            {
                                if (strGoalPlayer == kv.Value.playerName)
                                {
                                    MinuteStat ms = new MinuteStat();
                                    ms.goalMin = Int32.Parse(strGoalMin);

                                    ms.isOwnGoal = false;
                                    ms.name = strGoalPlayer;
                                    kv.Value.MinStat.Add(ms);
                                    kv.Value.goal++;

                                    bIsOwnGoal = false;
                                    break;
                                }
                            }
                        }
                        else if (strItemType.Contains("yellowcard.gif"))
                        {
                            string strCardPlayer = tr.TableCells[5].Text.Trim();
                            string strCardMin = tr.TableCells[3].Text.Trim();

                            foreach (KeyValuePair<int, PlayerStat> kv in awayPlayers)
                            {
                                if (strCardPlayer == kv.Value.playerName)
                                {
                                    match.awayYCard++; // red card
                                    kv.Value.yellowCard++;
                                    break;
                                }
                            }
                        }
                        else if (strItemType.Contains("redcard.gif"))
                        {
                            string strCardPlayer = tr.TableCells[5].Text.Trim();
                            string strCardMin = tr.TableCells[3].Text.Trim();

                            foreach (KeyValuePair<int, PlayerStat> kv in awayPlayers)
                            {
                                if (strCardPlayer == kv.Value.playerName)
                                {
                                    match.awayRCard++; // red card
                                    kv.Value.redCard++;
                                    break;
                                }
                            }
                        }
                        else if (strItemType.Contains("substition.gif"))
                        {
                            string strSubFacts = tr.TableCells[5].Text.Trim();
                            string[] separator = { "\r\n" };
                            string[] strPlayers = strSubFacts.Split(separator, System.StringSplitOptions.RemoveEmptyEntries);

                            string strSwitchoutPlayer = strPlayers[0].Remove(strPlayers[0].IndexOf('(')).Trim();
                            string strSubPlayer = strPlayers[1].Remove(strPlayers[0].IndexOf('(')).Trim();

                            PlayerStat subPlayer = new PlayerStat();
                            subPlayer.playerName = strSubPlayer;
                            subPlayer.isPlayerSub = true;
                            int number = GenPlayerNumber();
                            homePlayers.Add(number, subPlayer);

                            foreach (KeyValuePair<int, PlayerStat> kv in awayPlayers)
                            {
                                if (strSwitchoutPlayer == kv.Value.playerName)
                                {
                                    kv.Value.isSwitchOut = true;
                                    break;
                                }
                            }
                        }
                    }
                    #endregion AwayTeam
                }

                //add Marking Info
                foreach (KeyValuePair<int, PlayerStat> kv in homePlayers)
                {
                    kv.Value.markID = Marking.GetMarkingID(kv.Value.isPlayerSub, kv.Value.isSwitchOut);
                }
                foreach (KeyValuePair<int, PlayerStat> kv in awayPlayers)
                {
                    kv.Value.markID = Marking.GetMarkingID(kv.Value.isPlayerSub, kv.Value.isSwitchOut);
                }

                logger.Debug("#GetTeamStat# Ends. Return:true.");
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("#GetPlayerStat# Failed: Exception");
                logger.Error(ex.ToString());

                logger.Debug("#GetPlayerStat# Ends. Return:false.");
                return false;
            }
        }

        public int GenPlayerNumber()
        {
            return ((tempNumber++) % 30);
            //try
            //{
            //    return int.Parse(str);
            //}
            //catch (Exception ex)
            //{
            //    return -1 * ((tempNumber++) % 30);
            //}
        }

        private string GetSafeString(string str)
        {
            return ((string.IsNullOrWhiteSpace(str)) ? string.Empty : str.Trim());
        }
    }
}
